import React, { Component } from 'react';
import { Form, Input, Modal } from 'antd';
import './edit.less';
import * as sysApi from 'common/api/SysApi.js';

const FormItem = Form.Item;

/**
 * 编辑页面
 */
class Edit extends Component{
	
	constructor(props) {
	    super(props);
	    this.state = {
	    	initField: {
	    		userId: "",
				nickname: "",
				loginAccount: "",
			},
	    }
	}
	
	componentDidMount() {
		this.fetch(this.props.id);
	}
	
	componentWillReceiveProps(nextProps) {
		if(this.props.id != nextProps.id){
			this.fetch(nextProps.id);
		}
	}
	
	//请求数据
	fetch = (id) => {
		this.props.form.setFieldsValue(this.state.initField);
		if(id){
			sysApi.sysUserDetail({id}).then(result => {
				if(result && result.code == 20000){
					this.props.form.setFieldsValue(result.data);
				}
			})
		}
	}
	
	//保存
	save = () => {
		this.props.form.validateFields((err, values) => {
	      if(!err){
	      	sysApi.sysUserEdit(values).then(result => {
	      		if(result && result.code == 20000){
	      			this.props.editClose(true);
	      		}
	      	})
	      }
	    });
	}
	
	//取消
	cancel = () => {
		this.props.editClose(false);
	}
	
	render(){
		const { editTitle, editVisible } = this.props;
		const { getFieldDecorator } = this.props.form;
		return(
			<Modal
	          title={editTitle}
	          maskClosable={false}
	          keyboard={false}
	          visible={editVisible}
	          okText={"保存"}
	          onOk={this.save.bind(this)}
	          cancelText={"取消"}
			  onCancel={this.cancel.bind(this)}>
	          <Form onSubmit={this.save.bind(this)}>
					{getFieldDecorator('userId')(
			            <Input type="hidden"/>
		          	)}
					<FormItem label={(<span>姓名&nbsp;</span>)}>
					{getFieldDecorator('nickname', {
			            rules: [{ required: true, message: '请输入姓名!', whitespace: true }],
		          	})(
			            <Input autoComplete="off"/>
		          	)}
			        </FormItem>
			        <FormItem label={(<span>账号&nbsp;</span>)}>
					{getFieldDecorator('loginAccount', {
			            rules: [{ required: true, message: '请输入账号!', whitespace: true }],
		          	})(
			            <Input autoComplete="off"/>
		          	)}
			        </FormItem>
				</Form>
	        </Modal>
		)
	}
}

export default Form.create()(Edit);